package com.planw.beetl.utils;

import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.PopupChooserBuilder;
import com.intellij.ui.components.JBList;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class UiUtis {

    public interface ListSelectionListener {

        public void selected(int index);

    }


    public static JBPopup showListPopup(@NotNull String title,
                                        Project project,
                                        @Nullable final ListSelectionListener listener,
                                        @NotNull Object[] objs) {
        PopupChooserBuilder builder = createListPopupBuilder(title, listener, objs);
        JBPopup popup = builder.createPopup();
        setPositionForShown(popup, project);
        return popup;
    }

    protected static PopupChooserBuilder createListPopupBuilder(@NotNull String title,
                                                                @Nullable final ListSelectionListener listener,
                                                                @NotNull Object... objs) {
        final JBList list = new JBList(objs);
        PopupChooserBuilder builder = new PopupChooserBuilder(list);
        builder.setTitle(title);
        if (null != listener) {
            final Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    listener.selected(list.getSelectedIndex());
                }
            };
            builder.setItemChoosenCallback(new Runnable() {
                @Override
                public void run() {
                    listener.selected(list.getSelectedIndex());
//                    setActionForExecutableListener(runnable, listener);
                }
            });
        }
        return builder;
    }

//    private static void setActionForExecutableListener(Runnable runnable, ListSelectionListener listener) {
//        final Application application = ApplicationManager.getApplication();
//        application.runReadAction(runnable);
//    }


    private static void setPositionForShown(JBPopup popup, Project project) {
        Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
        if (null != editor) {
            popup.showInBestPositionFor(editor);
        } else {
            popup.showCenteredInCurrentWindow(project);
        }
    }
}
